/**
 * @Description: 工具类
 * @Author: lishibin
 * @Date: 14:29 2022/1/9
 * @version : V0.0.1-beta
 */
import CryptoJS from 'crypto-js';

/**
 * @description: aes_256_ecb 解密
 * @param {string} enc  密文
 * @param {string} key  key
 * @return {string} 明文
 */
export function decrypt(enc: string, key: string): string {
  return CryptoJS.AES.decrypt(
    CryptoJS.enc.Base64.stringify(CryptoJS.enc.Hex.parse(enc)),
    CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString()),
    {
      mode: CryptoJS.mode.ECB,
    },
  )
    .toString(CryptoJS.enc.Utf8)
    .toString();
}

/**
 * @description: aes_256_ecb 加密
 * @param {string} content  明文
 * @param {string} key  key
 * @return {string} 密文
 */
export const encrypt = (content: string, key: string): string => {
  const encrypted = CryptoJS.AES.encrypt(
    CryptoJS.enc.Utf8.parse(content),
    CryptoJS.enc.Utf8.parse(CryptoJS.MD5(key).toString()),
    {
      mode: CryptoJS.mode.ECB,
    },
  );
  return encrypted.ciphertext.toString();
};

/**
 * 将字符串转换成驼峰形式
 * @param str 需要转换的字符串
 * @returns 转换完成的字符串
 */
export const camelize = (str: string): string => {
  if (!str) return str;
  return str
    .replaceAll(/[-_\s]+(.)?/g, (_, c) => (c ? c.toUpperCase() : ''))
    .replace(/^[A-Z]/, (c) => c.toLowerCase());
};

/**
 * 获取对象及其原型链上的所有属性
 * @param obj  需要获取属性的对象
 * @returns   属性列表
 */
export const getAllPrototypeProperties = (obj: any): string[] => {
  const props: string[] = [];
  let current = obj;

  while (current && current !== Object.prototype) {
    const ownProps = Object.getOwnPropertyNames(current);
    props.push(...ownProps);
    current = Object.getPrototypeOf(current);
  }
  return [...new Set(props)]; // 去重
};
